// 
//  widgets.js
//  htdocs
//  
//  Created by Sean on 2008-10-15.
//  Copyright 2008 Sean. All rights reserved.
// 
//	We get to use jQuery for widget control

var OPW = (function(){ // OPW stands for OnePress Widgets
	return{
		utility: {} // init the utility object
	}
})();

OPW.dynamicLoader = (function(){
	var _inList = 0, _toObserve = [], _callbacks = [];
	
	return{
		construct: function(){
			// oberserve ul.widget-control-list to see if new widget has been added
			_observer = OPW.periodicalExecuter.call();
			_observer.init(OPW.dynamicLoader.observeWidgets,.5);
		},
		
		observeWidgets: function(){
			var nowInList = 0, // number of widgets in list
				toObserveString = '',
				i; // for loop
				
			toObserveString = _toObserve.join(' '); // form a space-separated string of widget names
			jQuery('ul.widget-control-list').children().each(function(){ // for each widget
				if(toObserveString.indexOf(this.id.split('-')[5]) != -1)
					nowInList++; // if the widget name is not in string, increment quantity in list
			});
			if(nowInList != _inList){ // if lists don't match
				_inList = nowInList;
				for(i=0; i < _callbacks.length; i++){
					_callbacks[i].call(); // call the callback for the widget
				}
			}
		},
		
		/**
		 *  Add widget to dynamicLoader
		 * 	@param string widget
		 *  @param function reference callback
		 **/
		add: function(widget,callback){
			_toObserve.push(widget);
			_callbacks.push(callback);
		}
	}
})();

/**
 * Utility class for executing code at defined increment
 **/
OPW.periodicalExecuter = (function(){
	var _freq, // how often, in ms
		_doaction; // store reference to setInterval so we can clear it when done
	
	return{
		callback: null, // callback to execute

		/**
		 *  Constructor
		 *  Assign values for object use
		 **/		
		init: function(callback,freq){
			this.callback = callback;
			_freq = freq;
			this.execute(); // start processing callback
		},
		
		/**
		 * Stop processing callback every freq
		 * Callback calls this when conditions met
		 */
		stop: function(){
			clearInterval(_doaction);
		},
		
		execute: function(){
			var _this = this; // tmp var to pass into closure
			_doaction = setInterval(function(){ _this.callback.call(_this); }, _freq * 1000); // start interval process
		},
		
		/**
		 * Method by which callback can be accessed publicly
		 **/
		getCallback: function(){
			return _callback;
		}
	}
});

OPW.dynamicLoader.construct();